package cn.itcast.algorithm.exercise;

import java.util.Scanner;

/**
 * 该题目的考点是测试栈的后进先出的数据结构
 * peek 获取栈顶元素 但不删除
 * pop 弹出栈顶元素（删除）
 * push 压栈
 * 左右括号匹配时要点是：即将入栈元素和栈顶元素成对匹配，如果匹配，栈顶元素出栈pop，否则新元素入栈。当栈中元素为空时，表示匹配完毕，数据合法
 * https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2?tpId=308&tqId=726&ru=/exam/oj&qru=/ta/algorithm-start/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D308
 * create by zhangtian105 on 2022/5/13
 */
public class ExerciseAB7 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in) ;
        String timeStr = scanner.nextLine() ;
        Integer timeNum = Integer.valueOf(timeStr) ;

        if (timeNum == null || timeNum <= 0) {
            return;
        }

        // 定义一个新的初始节点作为头结点，其中头结点无数据，头尾节点指向同一个位置
        DataNode head = new DataNode() ;
        DataNode tail = head ;
        tail.next = head.next = null ;
        while(scanner.hasNextLine()) {
            String command = scanner.nextLine() ;
            if (command == null || "".equals(command)) {
                continue;
            }

            if (command.startsWith("push")) {
                String[] arr = command.split(" ") ;

                if (arr.length != 2) {
                    continue;
                }

                int data = Integer.valueOf(arr[1]) ;

                // 此为头插法
                // head.next = new DataNode(data) ;
                // 此为尾插法
                tail.next = new DataNode(data) ;
                tail = tail.next ;
            }

            if (head.next == null) {
                System.out.println("error");
                continue;
            }

            if ("pop".equals(command)) {
                DataNode dataNode = head.next ;
                head = head.next ;
                System.out.println(dataNode.data);
            }

            if ("front".equals(command)) {
                DataNode headNode = head.next ;
                System.out.println(headNode.data);
            }

            timeNum -- ;

            if (timeNum < 0) {
                break;
            }
        }
    }

    static class DataNode {
        private DataNode next ;
        private int data ;

        public DataNode() {

        }

        public DataNode(int data) {
            this.data = data ;
        }
    }
}
